package cn.mumzone.pos.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.mumzone.basic.mvp.AbsPresenter;
import cn.mumzone.basic.net.http.callback.ApiCallBack;
import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.net.response.PageListResponse;
import cn.mumzone.basic.util.PatternUtils;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.event.GoodsAmountChangedEvent;
import cn.mumzone.pos.event.SettleSuccessEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.source.GoodsRepository;
import cn.mumzone.pos.model.source.MemberRepository;
import cn.mumzone.pos.presenter.contract.CashGoodsContract;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by JoeLjt on 2019/6/27.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class CashGoodsPresenter extends AbsPresenter<CashGoodsContract.View, GoodsRepository> {

    private static final int CODE_SEARCH_EMPTY = 504;

    private int mPageNum = 1;

    MemberRepository memberRepository;

    @Override
    protected void initOtherRepository() {
        super.initOtherRepository();
        memberRepository = new MemberRepository();
    }

    public void searchGoodsInfo(MemberEntity memberEntity, String goodsCode, final boolean isRefresh, boolean isScan) {
        ApiCallBack<PageListResponse<GoodsEntity>> callBack = new ApiCallBack<PageListResponse<GoodsEntity>>() {
            @Override
            public void onSuccess(PageListResponse<GoodsEntity> response) {
                mView.showSearchGoodsList(response.getList(), isRefresh);
                mPageNum++;
            }

            @Override
            public void onError(BaseResponse response) {
                if (response.getCode() == CODE_SEARCH_EMPTY) {
                    mView.showSearchGoodsError(response.getMsg());
                } else {
                    mView.showError(response.getMsg());
                }
            }
        };

        mPageNum = isRefresh ? 1 : mPageNum;

        mRepo.searchGoodsList("", memberEntity,
                goodsCode, StringUtils.get(mPageNum), StringUtils.get(AppConstants.PAGE_SIZE),
                isScan ? "1" : "0", callBack);
        addSubscrebe(callBack);
    }

    public void addGoodsToCart(final boolean isModify, Object cartList) {

        // 实时同步购物车数据
        clearCart();

        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.dismissLoadingDialog();
                mView.showAddGoodsSuccess(isModify);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.dismissLoadingDialog();
                mView.showError(response.getMsg());

            }
        };
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", JSON.toJSON(cartList));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        mRepo.addGoodsToCartBatch(body, callBack);
        addSubscrebe(callBack);
    }

    private void clearCart() {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showClearCart();
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());

            }
        };
        mRepo.clearCartGoods(callBack);
        addSubscrebe(callBack);
    }

    public void searchMember(String phone) {
        if (!PatternUtils.isMobileNO(phone)) {
            mView.showError("手机号格式不正确");
            return;
        }

        ApiCallBack<MemberEntity> callBack = new ApiCallBack<MemberEntity>() {
            @Override
            public void onSuccess(MemberEntity memberEntity) {
                mView.showSearchMemberSuccess(memberEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        memberRepository.getMemberInfoByPhone(phone, callBack);
        addSubscrebe(callBack);
    }

    public void doQuicklyAddMember(final String phone, final String name, String gender, String level) {
        if (!isInputLegal(name, phone, level)) {
            return;
        }
        ApiCallBack<MemberEntity> callBack = new ApiCallBack<MemberEntity>() {
            @Override
            public void onSuccess(MemberEntity s) {
                mView.showAddMemberSuccess(s);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        memberRepository.createNewMember(name, phone, gender, level, "",
                "", "", "", "", callBack);
    }

    public void initEvent() {

        Subscription removeGoodsListener = RxBus.getDefault()
                .toObservable(GoodsAmountChangedEvent.class)
                .subscribe(new Action1<GoodsAmountChangedEvent>() {
                    @Override
                    public void call(GoodsAmountChangedEvent amountChangedEvent) {
                        mView.onGoodsAmountChanged(amountChangedEvent.getGoodsList());
                    }
                });
        addSubscrebe(removeGoodsListener);

        Subscription settleSuccessListener = RxBus.getDefault()
                .toObservable(SettleSuccessEvent.class)
                .subscribe(new Action1<SettleSuccessEvent>() {
                    @Override
                    public void call(SettleSuccessEvent settleSuccessEvent) {
                        mView.showSettleSuccess();
                    }
                });
        addSubscrebe(settleSuccessListener);


    }


    private boolean isInputLegal(String name, String phone, String level) {

        if (TextUtils.isEmpty(name)) {
            mView.showError("请输入会员姓名");
            return false;
        }

        if (!PatternUtils.checkName(name)) {
            mView.showError("会员姓名不能输入特殊字符");
            return false;
        }

        if (!PatternUtils.isMobileNO(phone)) {
            mView.showError("手机号格式不正确");
            return false;
        }

        if (TextUtils.isEmpty(level)) {
            mView.showError("请选择会员等级");
            return false;
        }

        return true;
    }

}
